package ru.lenwp;

import org.springframework.context.support.GenericXmlApplicationContext;
import ru.lenwp.context.Context;
import ru.lenwp.model.Client;
import ru.lenwp.model.User;
import ru.lenwp.operation.OperationService;
import ru.lenwp.operation.admin.AdminOperationService;
import ru.lenwp.operation.admin.LoadUsersOperation;
import ru.lenwp.operation.client.ClientOperationService;
import ru.lenwp.util.ConsoleUtil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Locale;

/**
 * Created by Lenar on 27.06.2014.
 */
public class Main {
    public static void main(String[] args) throws Exception {
        Locale.setDefault(new Locale("en","EN"));
        Class.forName("oracle.jdbc.OracleDriver");
        Connection conn = null;
        GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
        ctx.load("applications_context.xml");
        ctx.refresh();

        try {
            conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "test_app", "12345");

            Context context = new Context(conn);
            while (true) {
                String login = ConsoleUtil.askString("Введите логин");
                String password = ConsoleUtil.askString("Введите пароль");
                OperationService operationService = null;
                String passwordFromDB = context.getUserDao().getPassword(login);
                    if (passwordFromDB != null && passwordFromDB.equals(password)) {
                        User user = context.getUserDao().getUser(login);
                        context.setCurrentUser(user);
                        operationService = (user instanceof Client) ? new ClientOperationService(context) : new AdminOperationService(context);
                    }
                if (operationService != null) {
                    operationService.runService();
                } else {
                    System.out.println("Введен не верно имя пользователя или пароль");
                }
            }
        }finally{
            if(conn != null){
                conn.close();
            }
        }
    }
}
